package com.example.shopp_2301.login

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.DialogInterface
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.mvvm.BaseActivity
import com.example.shopp_2301.R
import com.example.shopp_2301.databinding.ActivityLoginCodeBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 验证码60秒后可再次获取
 * 没有验证码，登录按钮按钮不可用
 */
@Route(path = "/app/LoginCodeActivity")
class LoginCodeActivity : BaseActivity<ActivityLoginCodeBinding,LoginViewModel>() {

    lateinit var notification:Notification//定义通知
    override fun initView() {
        binding.sendCode.setOnClickListener {
            if(binding.etPhone.text.toString().isEmpty()){
                ToastUtils.showLong("手机号不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileSimple(binding.etPhone.text.toString())){
                ToastUtils.showLong("手机号格式不正确")
                return@setOnClickListener
            }
            //调用发送验证码的接口
            viewModel.sendCode(binding.etPhone.text.toString())
            //验证码60秒后可再次获取
            //delay延迟一秒，可以在线程内执行  在指定作用域中直接执行
            lifecycleScope.launch {
                for (i in 60 downTo  1){
                    delay(1000)//模拟一秒的效果
                    binding.sendCode.text = "$i 秒后获取"
                    binding.sendCode.isEnabled = false
                    if(i==1){
                        binding.sendCode.text = "获取验证码"
                        binding.sendCode.isEnabled = true
                    }
                }
            }
        }
        binding.btnLoginCode.setOnClickListener {
            val phone = binding.etPhone.text.toString()
            val code = binding.etCode.text.toString()
            if(phone.isEmpty()||code.isEmpty()){
                ToastUtils.showLong("手机号和验证码均不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileSimple(binding.etPhone.text.toString())){
                ToastUtils.showLong("手机号格式不正确")
                return@setOnClickListener
            }
            if(!binding.cb.isChecked){
                ToastUtils.showLong("请先勾选同意协议")
                return@setOnClickListener
            }
            viewModel.loginCode(code,phone)
        }
        //点击文字跳转到对应页面 （结束当前页面）
        binding.goLogin.setOnClickListener {
            finish()
            ARouter.getInstance().build("/app/LoginActivity").navigation()
        }
        //没有验证码，登录按钮按钮不可用
        binding.btnLoginCode.isEnabled = false//是否可点击
        //binding.btnLoginCode.isVisible = false//是否可见
        binding.etCode.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if(binding.etCode.text.toString().length==6){
                    binding.btnLoginCode.isEnabled = true
                }else{
                    binding.btnLoginCode.isEnabled = false
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })
        //显示富文本
        val spannableStringBuilder = SpannableStringBuilder(binding.cb.text.toString())//将对应内容设为富文本
        //设置颜色---文字颜色、背景色 设置边框颜色
        spannableStringBuilder.setSpan(ForegroundColorSpan(Color.RED),1,4,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE)
        //设置点击事件
        val clickableSpan = object :ClickableSpan(){
            override fun onClick(widget: View) {
                ARouter.getInstance().build("/app/WebViewActivity").withString("url","http://www.baidu.com").navigation()
            }
        }
        val clickableSpan1 = object :ClickableSpan(){
            override fun onClick(widget: View) {
                ARouter.getInstance().build("/app/WebViewActivity").withString("url","http://www.bilibili.com").navigation()
            }
        }
        spannableStringBuilder.setSpan(clickableSpan,7,13,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE)
        spannableStringBuilder.setSpan(clickableSpan1,14,20,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE)
        binding.cb.movementMethod = LinkMovementMethod.getInstance()
        binding.cb.text = spannableStringBuilder

    }

    override fun initData() {
        //获取验证码
        viewModel.sendCodeSuccess.observe(this){
            if(it.code==200){
                ToastUtils.showLong(it.message)
                //直接将验证码显示到对应位置
                //binding.etCode.setText(it.data.content.substring(8,14))
                //优化升级，发送通知
                //通知管理器
               /* val notificationManager =
                    getSystemService(NOTIFICATION_SERVICE) as NotificationManager

                if(Build.VERSION.SDK_INT>Build.VERSION_CODES.O){
                    val notificationChannel = NotificationChannel("id","name",NotificationManager.IMPORTANCE_DEFAULT)
                    notificationManager.createNotificationChannel(notificationChannel)
                     notification= Notification.Builder(this)
                        .setChannelId("id")
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentTitle("短信通知")
                        .setContentText(it.data.content.substring(8,14))
                        .build()
                }else{
                    notification= Notification.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentTitle("短信通知")
                        .setContentText(it.data.content.substring(8,14))
                        .build()
                }
                notificationManager.notify(1,notification)*/
                //弹出alertDialog
                val alertDialog = AlertDialog.Builder(this)
                    .setTitle("验证码提示")
                    .setMessage(it.data.content.substring(8,14))
                    .setPositiveButton("确定",object :DialogInterface.OnClickListener{
                        override fun onClick(dialog: DialogInterface?, which: Int) {
                            ToastUtils.showLong("1234")
                        }
                    })
                    .setNegativeButton("取消"){ _,_->
                        ToastUtils.showLong("点击了取消")
                    }
                    .create()
                    .show()

            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.sendCodeFail.observe(this){
            ToastUtils.showLong(it)
        }
        //验证码登录
        viewModel.loginCodeSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                //保存token
                SPUtils.getInstance().put("token",it.data.token)
                //保存手机
                SPUtils.getInstance().put("phone",it.data.phone)
                finish()
                ARouter.getInstance().build("/app/ShopActivity").navigation()
            }
        }
        viewModel.loginCodeFail.observe(this){
            ToastUtils.showLong(it)
        }
    }

    override fun getViewModel(): Class<LoginViewModel> {
        return LoginViewModel::class.java
    }

    override fun getLayout(): Int  = R.layout.activity_login_code

}